<?php
declare (strict_types = 1);

namespace app\api\validate;


use think\Validate;

class User extends Validate {

    protected $rule = [
        "tel" => "require|length:11",
        "code" => "require|length:4|checkCode",
        "type" => "require|in:1,2",
        "username" => "checkUsername",
        "name" => "require",
        "sex" => "require|number|between:0,1,2",
        "birthday" => "require|dateCheck",
        "token" => "require",
    ];

    protected $message = [
        "tel.require" => "联系电话不能为空",
        "tel.length" => "联系电话不正确",
        "code.require" => "验证码不能为空",
        "code.length" => "验证码不正确",
        "type.require" => "类型不能为空",
        "type.in" => "类型不正确",
        "name.require" => "姓名不能为空",
        "sex.require" => "性别不能为空",
        "sex.number" => "性别格式不正确",
        "sex.between" => "性别不正确",
        "birthday.require" => "生日不能为空",
        "token.require" => "请重新登录",
    ];
    /**
     *  场景使用
     * @var scene
     */
    protected $scene = [
        "send_code" => ["tel"],
        "login" => ["tel", "code", "type"],
        "updateUserInfo" => ["username", "name", "sex", "birthday", "token"],
    ];

    /**
     *  验证码是否正确
     *
     * @param $value
     * @param $rule
     * @param array $data
     * @return bool|string
     */
    public function checkCode($value, $rule, $data = []) {
        if (cache(config("redis.code_pre").$data["tel"]) != $value) {
            return "验证码不正确 ";
        }

        return true;
    }

    /**
     *  检查username
     *
     * @param $value
     * @param $rule
     * @param array $data
     * @return bool|string
     */
    public function checkUsername($value, $rule, $data = []) {
        $userInfo = cache(config("redis.token_pre") . $data["token"]);
        if (!$userInfo || !isset($userInfo["id"])) {
            return "请重新登录";
        }
        if (isset($userInfo["is_updated_username"]) && $userInfo["is_updated_username"] == 1
            && $value != "" && $value != $userInfo["username"]){
            return "用户名不能再次修改了";
        }else if (isset($userInfo["is_updated_username"]) && $userInfo["is_updated_username"] == 0 && $value == "") {
            return "用户名传参失败";
        }else if (isset($userInfo["is_updated_username"]) && $userInfo["is_updated_username"] == 1 && $value == "") {
            return true;
        }

        $result = \app\model\mysql\User::isExistUsername($userInfo["id"], $value);
        if ($result) {
            return "该用户已存在";
        }

        return true;
    }

    /**
     * 日期格式检测
     * @param $value
     * @param $rule
     * @param array $data
     * @return bool|string
     */
    public function dateCheck($value, $rule, $data = []) {
        $patten = "/^\d{4}(\-|\/|.)\d{2}(\-|\/|.)\d{2}$/";

        if (preg_match($patten, $value) != 1){
            return "日期格式不正确";
        }

        return true;
    }

}